package com.neasho.neashoadminv1.infrastructure.template

import com.neasho.neashoadminv1.infrastructure.domain.generator.AppTableView
import freemarker.template.Configuration
import freemarker.template.Template
import freemarker.template.TemplateExceptionHandler
import org.slf4j.Logger
import org.springframework.util.ClassUtils
import java.io.File
import java.io.FileWriter

private val log: Logger = org.slf4j.LoggerFactory.getLogger("FreemarkerTemplate")

fun configureFreeMarker(): Configuration {
    val cfg = Configuration(Configuration.VERSION_2_3_32)

    // 模板目录设置
    val classpath = ClassUtils.getDefaultClassLoader()?.getResource("templates/generator_v1")?.path
    cfg.setDirectoryForTemplateLoading(File(classpath?:""))

    // 配置设置
    cfg.defaultEncoding = "UTF-8"
    cfg.templateExceptionHandler = TemplateExceptionHandler.RETHROW_HANDLER
    cfg.logTemplateExceptions = false
    cfg.wrapUncheckedExceptions = true
    cfg.fallbackOnNullLoopVariable = false

    return cfg
}

/**
 * 渲染模板引擎
 */
fun renderSimpleTemplate(tplName: String, distFile: File, context: Any) {
    val cfg = configureFreeMarker()
    val template: Template = cfg.getTemplate(tplName)
    if (!distFile.parentFile.exists()) {
        distFile.parentFile.mkdirs()
    }
    val out = FileWriter(distFile)
    try {
        template.process(context, out)
    } catch (e: Exception) {
        log.error("failed to render file: $distFile", e)
    }finally {
        out.close()
    }
}